package com.itheima.servlet.response;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

// 演示响应字节数据
@WebServlet("/resp04")
public class ResponseDemo04 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1.读取文件
        // FileInputStream fis = new FileInputStream("D:\\code\\IdeaProjects\\JavaUp162\\request-response-demo\\src\\main\\webapp\\imgs\\reg_bg_min.jpg");
        // 获取Tomcat的部署路径
        String realPath = getServletContext().getRealPath("imgs\\reg_bg_min.jpg");
        System.out.println("realPath = " + realPath);
        FileInputStream fis = new FileInputStream(realPath);

        // 2.获取response字节输出流
        ServletOutputStream out = response.getOutputStream();

        // 3.完成流的copy
        // byte[] buf = new byte[1024]; // 保存读取的数据
        // int len; // 保存读取的数量
        // while ((len = fis.read(buf)) != -1) {
        //     out.write(buf, 0, len);
        // }
        IOUtils.copy(fis, out); // copy方法内部会复制数据

        // response得到的输出流有Tomcat关闭, 我们自己创建的FileInputStream,需要自己关闭
        fis.close();
    }
}
